package com.mjlf.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @auther a123
 * @create 2018-08-25 16:03
 * @desc
 */
public final class ReflectionUtil {

    private static Logger logger = LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 实例化对象
     * @param cls
     * @return
     */
    public static Object newInstance(Class<?> cls){
        Object object;
        try{
            object = cls.newInstance();
        }catch (Exception e){
            logger.error("实例化类失败", e);
            throw new RuntimeException(e);
        }
        return object;
    }

    /**
     * 使用反射调用方法
     * @param obj
     * @param method
     * @param args
     * @return
     */
    public static Object invokeMethod(Object obj, Method method, Object ...args){
        Object result;
        try{
            result = method.invoke(obj, args);
        }catch (Exception e){
            logger.error("调用方失败", e);
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 设置属性
     * @param obj
     * @param field
     * @param value
     */
    public static void setField(Object obj, Field field, Object value){
        try{
            field.setAccessible(true);
            field.set(obj, value);
        }catch (Exception e){
            logger.error("设置属性失败", e);
            throw new RuntimeException(e);
        }
    }
}
